/*
 * @Author: yxfan
 * @Date: 2025-04-20 15:54:34
 * @LastEditTime: 2025-05-12 21:17:09
 * @FilePath: \umi-demo\src\pages\demo\TableInput\demo.tsx
 * @Description:
 */
import React, { useState, useRef, useEffect } from 'react';
import { Card, Button, Space, Form } from 'antd';
import TableInput, { TableInputRef } from './index';

// 定义表格数据的接口
interface TableRowData {
    id: string;
    name: string;
    age: number | null;
    gender: string | null;
}

const Demo: React.FC = () => {
    // 创建 ref 用于引用 TableInput 组件
    const tableInputRef = useRef<TableInputRef>(null);
    const [form] = Form.useForm();
    // 初始数据
    const [tableData, setTableData] = useState<TableRowData[]>([
        { id: '1', name: '张三', age: 25, gender: 'male' },
        { id: '2', name: '李四', age: 30, gender: 'male' },
        { id: '3', name: '王五', age: 28, gender: 'female' },
    ]);

    // 表单验证规则
    const nameValidator = async (
        value: string,
        rowData: TableRowData,
        rowIndex: number,
    ) => {
        if (!value) return '姓名不能为空';
        if (value.length < 2) return '姓名至少需要2个字符';
        return '';
    };

    const nameRepeatValidator = async (
        value: string,
        rowData: TableRowData,
        rowIndex: number,
    ) => {
        // 如果姓名为空，不进行重复检查（让 nameValidator 处理空值验证）
        if (!value) return '';

        // 检查姓名是否重复
        const duplicateName = tableData.findIndex(
            (item, index) => item.name === value && index !== rowIndex,
        );

        if (duplicateName !== -1) return '姓名不能重复';
        return ''; // 验证通过时必须返回空字符串
    };
    const ageValidator = async (value: number) => {
        if (!value && value !== 0) return '年龄不能为空';
        if (value < 18) return '年龄必须大于等于18岁';
        if (value > 100) return '年龄必须小于等于100岁';
        return '';
    };

    // 生成新行的默认数据
    const createNewRow = () => {
        const newId = (
            parseInt(tableData[tableData.length - 1]?.id || '0') + 1
        ).toString();
        return { id: newId, name: '', age: null, gender: null, isNewRow: true };
    };

    // 验证所有数据
    const validateAll = async () => {
        try {
            // 调用 TableInput 组件的 validateFields 方法
            const validData = await tableInputRef.current?.validateFields();
            console.log('验证通过，当前表格数据:', validData);
            return true;
            // 在实际应用中，这里可以进行表单提交
        } catch (error) {
            console.error('表单验证失败:', error);
            return false;
            // 在实际应用中，这里可以显示错误提示
        }
    };

    // 表格列定义
    const columns = [
        {
            title: 'ID',
            dataIndex: 'id',
            key: 'id',
            width: 100,
        },
        {
            title: '姓名',
            dataIndex: 'name',
            key: 'name',
            fieldType: 'Input',
            fieldRules: [
                { validator: nameValidator },
                { validator: nameRepeatValidator },
            ],
        },
        {
            title: '年龄',
            dataIndex: 'age',
            key: 'age',
            fieldType: 'Input',
            fieldRules: [{ validator: ageValidator }],
        },
        {
            title: '性别',
            dataIndex: 'gender',
            key: 'gender',
            fieldType: 'Select',
            options: [
                { label: '男', value: 'male' },
                { label: '女', value: 'female' },
            ],
        },
    ];

    async function handleSubmit() {
        const values = await form.validateFields();
        console.log('form values', values);
    }
    return (
        <div style={{ padding: 24 }}>
            <Form form={form}>
                <Form.Item
                    label="label"
                    name="params"
                    initialValue={tableData}
                    validateTrigger={[]}
                    rules={[
                        {
                            validator: async () => {
                                const res = await validateAll();
                                if (res) {
                                    return Promise.resolve();
                                } else {
                                    return Promise.reject();
                                }
                            },
                        },
                    ]}
                >
                    <TableInput
                        ref={tableInputRef}
                        // value={tableData}
                        // onChange={setTableData}
                        columns={columns as any}
                        autoAddRow={true}
                        defaultNewRow={createNewRow}
                    />
                </Form.Item>
            </Form>
            <Button onClick={handleSubmit}>form表单校验</Button>
            {/* <Card title="表格内嵌表单示例">
                <Space style={{ marginTop: 16 }}>
                    <Button onClick={validateAll}>验证数据</Button>
                </Space>
            </Card> */}
        </div>
    );
};

export default Demo;
